<!-- 分诊规则 -->
<template>
  <div class="main-content-container">
    <el-row>
      <el-col>
        <p class="font-size-14-y">分诊轮排规则</p>
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <p class="font-size-14-y">咨询师自动轮排
          <el-switch v-model="advSwitch" active-value="开启" inactive-value="关闭" :disabled="counselorTable.length > 0?false:true" @change="counselorSwith(advSwitch)" />
          <span class="spans font-size-14-y">轮排时，将由系统自动分配咨询师</span>
        </p>
      </el-col>
    </el-row>
    <div class="box-show">
      <el-table ref="singleTable" :data="counselorTable" border :row-class-name="tableColor" height="300">
        <el-table-column label="序号" prop="sort" :show-overflow-tooltip="true" />
        <el-table-column label="姓名" prop="manName" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <!-- <el-input v-if="scope.$index===counselorTable.length-1&&flag" v-model="scope.row.manName" placeholder="请输入姓名" clearable /> -->
            <el-select v-if="scope.$index===counselorTable.length-1&&flag" v-model="scope.row.manName" value-key="id" @change="handleSelectCounselor">
              <el-option v-for="item in consultantList" :key="item.id" :label="item.usrName" :value="item" />
            </el-select>
            <span v-else>{{ scope.row.manName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="分诊比例" prop="triageScale" :show-overflow-tooltip="true" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <div v-if="scope.$index===counselorTable.length-1&&flag">
              <el-button type="text" @click="saveCounselorBtn">保存</el-button>
              <el-button type="text" @click="cancelCounselorBtn(scope.$index, counselorTable)">取消</el-button>
            </div>
            <div v-else>
              <el-button v-if="scope.$index!==0" type="text" @click="moveUp(scope.$index,counselorTable,false)">上移</el-button>
              <el-button v-if="scope.$index!==counselorTable.length-1" type="text" @click="moveDown(scope.$index,counselorTable,false)">下移</el-button>
              <el-button type="text" @click="deleteCounselorBtn(scope.row.id)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="margin-top: 20px" class="buttons">
      <el-button :disabled="flag" @click="addCounselorBtn">添加</el-button>
    </div>
    <el-row>
      <el-col>
        <p>
          <span class="font-size-14-y">主治医生自动轮排</span>
          <el-switch v-model="docSwitch" active-value="开启" inactive-value="关闭" :disabled="doctorTable.length > 0?false:true" @change="doctorSwith(docSwitch)" />
          <span class="spans font-size-14-y">轮排时，仅做记录，将由人工分配主治医生</span>
        </p>
      </el-col>
    </el-row>
    <div class="box-show">
      <el-table ref="doctorTableRef" v-loading="loading" border height="300" :data="doctorTable" style="width: 100%;" row-key="id" :tree-props="{children: 'list', hasChildren: 'hasChildren'}">
        <el-table-column width="80" />
        <el-table-column label="咨询分类" prop="consultType" :show-overflow-tooltip="true">
          <template v-if="!scope.row.second" slot-scope="scope" :show-overflow-tooltip="true">
            <span>{{ scope.row.consultType }}</span>
          </template>
        </el-table-column>
        <el-table-column label="序号" prop="sort" :show-overflow-tooltip="true" />
        <el-table-column label="姓名" prop="manName" :show-overflow-tooltip="true" />
        <el-table-column label="分诊比例" prop="triageScale" :show-overflow-tooltip="true" />
        <el-table-column label="操作">
          <template v-if="scope.row.second" slot-scope="scope">
            <el-button v-if="scope.row.place!=='min'" type="text" @click="moveUp(scope.row.sort-1,scope.row.data,true)">上移</el-button>
            <el-button v-if="scope.row.place!=='max'" type="text" @click="moveDown(scope.row.sort-1,scope.row.data,true)">下移</el-button>
            <!-- <el-button type="text" @click="editDoctorBtn(scope.row)">修改</el-button> -->
            <el-button type="text" @click="deleteDoctorBtn(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="margin-top: 20px" class="buttons">
      <el-button @click="addDoctorTable">添加</el-button>
    </div>
    <Dialog :title="title" :visible="visible" :button-text="textBtn" @confirm="handleConfirm" @close="handleClose">
      <el-form ref="doctorFormRef" :model="doctorForm" :rules="doctorFormRules" label-width="100px">
        <el-form-item label="咨询分类：" prop="consultType">
          <el-row>
            <el-col :span="22">
              <el-select v-model="doctorForm.consultType" value-key="id" :disabled="title === '修改医生'?true:false" @change="handleSelectConsulting">
                <el-option v-for="item in consultingOptions" :key="item.id" :label="item.name" :value="item.name" />
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="主治医生：" prop="manName">
          <el-row>
            <el-col :span="22">
              <!-- <el-input v-model="doctorForm.manName" /> -->
              <el-select v-model="doctorForm.manName">
                <el-option v-for="item in doctorOptions" :key="item.id" :label="item.usrName" :value="item.usrName" />
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>

<script>
import Dialog from "@/components/Dialog";
import { tableColor } from '@/utils/common.js';
export default {
  components: {
    Dialog,
  },
  data() {
    return {
      tableColor,
      advSwitch: '关闭',
      docSwitch: '关闭',
      counselorTable: [],
      doctorTable: [],
      doctorForm: {},
      seleteType: '', // 选中的分类名称
      consultingOptions: [], // 咨询分类
      consultantList: [], //  咨询师
      doctorOptions: [],
      consultantData: {},
      title: '',
      textBtn: '保存',
      visible: false,
      loading: false,
      flag: false,
      doctorFormRules: {
        consultType: [
          { required: true, message: '请选择咨询分类', trigger: 'change' },
        ],
        manName: [
          { required: true, message: '请输入医生姓名', trigger: 'blur' },
        ],
      },
    };
  },
  mounted() {
    this.getCounselorData();
    this.getDoctorList();
    this.getSwitchState();
  },
  methods: {
    async getSwitchState() {
      const res = await this.$api['reception/triage/getSwitch']();
      if (res.code !== 200) return this.$message.error(res.msg);
      this.advSwitch = res.data.advSwitch;
      this.docSwitch = res.data.docSwitch;
    },
    counselorSwith(val) {
      this.updateSwitch({ advSwitch: val });
    },
    doctorSwith(val) {
      this.updateSwitch({ docSwitch: val });
    },
    async updateSwitch(val) {
      const res = await this.$api['reception/triage/updateSwitch'](val);
      if (res.code !== 200) return this.$message.error('状态更改失败！');
      this.$message.success('状态更改成功！');
      this.getSwitchState();
    },
    async getCounselorData() {
      this.loading = true;
      const res = await this.$api['reception/triage/adviserList']({ query: { type: '咨询师' }});
      this.loading = false;
      if (res.code !== 200) return this.$message.error('获取咨询师列表数据失败！');
      this.counselorTable = res.data;
      // this.counselorTable = [];
      if (this.counselorTable.length < 1) {
        this.advSwitch = '关闭';
      }
    },
    async getDoctorList() {
      this.loading = true;
      const res = await this.$api['reception/triage/doctorList']({ query: { type: '主治医生' }});
      this.loading = false;
      if (res.code !== 200) return this.$message.error('获取主治医生列表数据失败！');
      this.dataListHandle(res.data); // 数据处理
      this.doctorTable = res.data;
      // this.doctorTable = [];
      if (this.doctorTable.length < 1) {
        this.docSwitch = '关闭';
      }
    },
    dataListHandle(list, copyList) {
      list.forEach(item => {
        if (item.list && item.list.length > 0) {
          item.list = this.dataListHandle(item.list, JSON.parse(JSON.stringify(item.list)));
        }
        if (copyList) {
          this.$set(item, 'data', copyList);
        }
      });
      return list;
    },
    // 添加咨询师
    addCounselorBtn() {
      this.counselorTable.push({
        manName: '',
        sort: this.counselorTable.length + 1,
        type: '咨询师',
      });
      this.attributionConsultant();
      this.flag = true;
    },
    async attributionConsultant() {
      const res = await this.$api['data/hospitalStaff/getAllByJobName']({ hospitalJobName: "咨询师" });
      if (res.code !== 200) return;
      this.consultantList = res.data;
    },
    handleSelectCounselor(item) {
      this.consultantData = { manId: item.id, manName: item.usrName };
    },
    async saveCounselorBtn() {
      const res = await this.$api['reception/triage/addTriageRule']({ ...this.counselorTable.pop(), ...this.consultantData });
      if (res.code !== 200) return this.$message.error('添加咨询师失败！');
      this.getCounselorData();
      this.flag = false;
    },
    cancelCounselorBtn(index, data) {
      data.splice(index, 1);
      this.flag = false;
    },
    // 上移
    moveUp(index, data, tree) {
      console.log(index, data, tree, '上移');
      if (index > 0) {
        const upDate = data[index - 1];
        data.splice(index - 1, 1);
        data.splice(index, 0, upDate);
      } else {
        this.$message.info('已经是第一条，不可上移');
      }
      this.moveTriageRuleData(data, tree);
    },
    // 下移
    moveDown(index, data, tree) {
      console.log(index, data, tree, '下移');
      if ((index + 1) === data.length) {
        this.$message.info('已经是最后一条，不可下移');
      } else {
        const downDate = data[index + 1];
        data.splice(index + 1, 1);
        data.splice(index, 0, downDate);
      }
      this.moveTriageRuleData(data, tree);
    },
    async moveTriageRuleData(data, tree) {
      console.log(data, tree, '移后');
      const res = await this.$api['reception/triage/moveTriageRule']({ list: data });
      if (res.code !== 200) return this.$message.error('操作失败！');
      if (tree) {
        this.getDoctorList();
      } else {
        this.getCounselorData();
      }
    },
    // 删除
    deleteCounselorBtn(id) {
      this.deleteTriageRule(id, true);
    },
    async deleteTriageRule(id, show) {
      const confirmResult = await this.$confirm('请确认是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch((err) => err);
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除');
      }
      const res = await this.$api['reception/triage/deleteTriageRule']({ id: id });
      if (res.code !== 200) return this.$message.error('删除失败！');
      this.$message.success('删除成功！');
      if (show) {
        this.getCounselorData();
      } else {
        this.getDoctorList();
      }
    },
    // 添加医生
    addDoctorTable() {
      this.title = '添加医生';
      this.visible = true;
      this.getConsultingData();
      this.getDoctorData();
    },
    // 咨询分类
    async getConsultingData() {
      const consultingData = await this.$api['reception/subscribe/consulttype']();
      if (consultingData.code === 200) {
        this.consultingOptions = consultingData.data.result;
      }
    },
    // 医生
    async getDoctorData() {
      const res = await this.$api['reception/subscribe/getAllByJobName']({ hospitalJobName: '主治医生' });
      if (res.code === 200) {
        this.doctorOptions = res.data;
      }
    },
    handleSelectConsulting(val) {
      this.seleteType = val;
    },
    handleConfirm() {
      this.$refs.doctorFormRef.validate(async(valid) => {
        if (valid) {
          if (this.title === '添加医生') {
            this.doctorForm.type = "主治医生";
            this.doctorTable.map(item => {
              if (item.consultType === this.seleteType) {
                this.doctorForm.sort = item.list.length + 1;
              }
            });
            this.loading = true;
            const res = await this.$api['reception/triage/addTriageRule']({ ...this.doctorForm });
            this.loading = false;
            if (res.code !== 200) return this.$message.error('添加医生失败！');
            this.$message.success('添加医生成功！');
          } else {
            this.loading = true;
            const res = await this.$api['reception/triage/editTriageRule']({ ...this.doctorForm });
            this.loading = false;
            if (res.code !== 200) return this.$message.error('修改医生失败！');
            this.$message.success('修改医生成功！');
          }
          this.visible = false;
          this.getDoctorList();
        }
      });
    },
    handleClose() {
      this.visible = false;
      this.$refs.doctorFormRef.resetFields();
    },
    // editDoctorBtn(row) {
    //   this.doctorForm = row;
    //   this.title = '修改医生';
    //   this.visible = true;
    //   this.getConsultingData();
    //   this.getDoctorData();
    // },
    deleteDoctorBtn(id) {
      this.deleteTriageRule(id, false);
    },
  },
};
</script>

<style lang="scss" scoped>
.spans{
  margin-left: 12px;
}

.box-show{
  padding-bottom: 20px;
  margin-top: 20px;
}
</style>

